{% extends "base.html" %}
{% load static %}

{% block title %}{{ event.title }} - 本地有约{% endblock %}

{% block content %}
<!-- 引入百度地图API -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=rUiyl00fneDC8rieZJagiXxwyDl7ZYje"></script>

<style>
    .icon-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .text-warning {
        color: #ffc107 !important;
    }

    .fixed-bottom {
        box-shadow: 0 -2px 20px rgba(0,0,0,0.1);
        padding: 12px;
        background: white;
    }

    .activity-content ul {
        color: #666;
        line-height: 1.6;
    }

    .activity-content ul li {
        margin-bottom: 4px;
    }

    #map-container {
        border-radius: 8px;
        overflow: hidden;
        height: 250px;
    }

    .map-marker-popup {
        max-width: 200px;
    }

    /* 活动封面图样式 */
    .event-cover-container {
        height: 250px;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f8f9fa;
        border-radius: 8px;
    }

    .event-cover-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        background-color: #f8f9fa;
    }

    /* 路线规划样式 */
    .route-info {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 12px;
        margin-top: 10px;
        display: none;
    }

    .route-step {
        display: flex;
        align-items: flex-start;
        margin-bottom: 8px;
        font-size: 0.9rem;
    }

    .route-step:last-child {
        margin-bottom: 0;
    }

    .step-icon {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.7rem;
        margin-right: 10px;
        flex-shrink: 0;
    }

    .step-content {
        flex: 1;
    }

    /* 评论区样式 */
    .comment-item {
        transition: all 0.3s ease;
        padding: 10px;
        border-radius: 8px;
        position: relative;
    }

    .comment-item:hover {
        background-color: #f8f9fa;
    }

    .reply-item {
        border-left: 3px solid var(--primary-color);
        background-color: #f8f9fa;
        border-radius: 0 8px 8px 0;
        padding: 8px 12px;
        margin: 5px 0;
        position: relative;
    }

    .reply-input {
        transition: all 0.3s ease;
    }

    .like-btn.active .fa-thumbs-up {
        color: var(--primary-color);
    }

    .replies-list {
        max-height: 300px;
        overflow-y: auto;
    }

    .comment-actions {
        opacity: 0.6;
        transition: opacity 0.3s ease;
    }

    .comment-item:hover .comment-actions {
        opacity: 1;
    }

    /* 删除按钮样式 */
    .delete-comment-btn {
        color: #dc3545;
        opacity: 0.7;
        transition: all 0.3s ease;
        padding: 4px;
        border-radius: 4px;
    }

    .delete-comment-btn:hover {
        opacity: 1;
        background-color: rgba(220, 53, 69, 0.1);
    }

    /* 新布局样式 */
    .main-visual-section {
        margin-bottom: 24px;
    }

    .info-card {
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        border: none;
        margin-bottom: 20px;
    }

    .info-card .card-body {
        padding: 20px;
    }

    .card-title-section {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
    }

    .card-title-section i {
        font-size: 1.2rem;
    }

    /* 响应式调整 */
    @media (max-width: 768px) {
        .main-visual-section .col-md-6 {
            margin-bottom: 20px;
        }

        .event-cover-container {
            height: 200px;
        }
    }

    @media (max-width: 576px) {
        .fixed-bottom {
            padding: 10px 15px;
        }

        .activity-content img {
            max-width: 100%;
            height: auto;
        }

        .replies-list {
            max-height: 200px;
        }

        .comment-item {
            padding: 8px;
        }

        .event-cover-container {
            height: 180px;
        }

        .info-card .card-body {
            padding: 16px;
        }
    }
</style>

<!-- 主要内容 -->
<div class="container mt-3">
    <!-- 顶部图片和地图并排布局 -->
    <div class="main-visual-section">
        <div class="row g-4">
            <!-- 活动封面图 -->
            <div class="col-md-6">
                <div class="card info-card h-100">
                    <div class="card-body p-0">
                        <div class="event-cover-container h-100">
                            {% if event_images and event_images.first %}
                                <img src="{{ event_images.first.image.url }}" class="event-cover-img" alt="活动封面">
                            {% else %}
                                <img src="https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80"
                                     class="event-cover-img" alt="活动封面">
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 地图定位 -->
            <div class="col-md-6">
                <div class="card info-card h-100">
                    <div class="card-body">
                        <div class="card-title-section">
                            <i class="fas fa-map-marked-alt text-primary me-2"></i>
                            <h6 class="card-title fw-bold mb-0">地图定位</h6>
                        </div>
                        <!-- 百度地图容器 -->
                        <div id="map-container" class="rounded mb-3"></div>

                        <!-- 活动签到功能 -->
                        <div class="checkin-section mt-4">
                            <div class="card-title-section mb-3">
                                <i class="fas fa-qrcode text-success me-2"></i>
                                <h6 class="card-title fw-bold mb-0">活动签到</h6>
                            </div>

                            {% now "Y-m-d H:i:s" as current_time %}

                            {% if user_registered %}
                                {% if not has_checked_in %}
                                    {% if current_time < event.start_time %}
                                    <!-- 活动未开始 -->
                                    <div class="checkin-status text-center p-3 bg-light rounded">
                                        <i class="fas fa-clock fa-2x text-warning mb-2"></i>
                                        <p class="mb-2">活动尚未开始</p>
                                        <small class="text-muted">开始时间: {{ event.start_time|date:"m月d日 H:i" }}</small>
                                    </div>
                                    {% elif current_time > event.end_time %}
                                    <!-- 活动已结束 -->
                                    <div class="checkin-status text-center p-3 bg-light rounded">
                                        <i class="fas fa-ban fa-2x text-danger mb-2"></i>
                                        <p class="mb-2">活动已结束</p>
                                        <small class="text-muted">无法签到</small>
                                    </div>
                                    {% else %}
                                    <!-- 可以签到 -->
                                    <div class="checkin-status text-center p-3 bg-light rounded mb-3">
                                        <i class="fas fa-map-marker-alt fa-2x text-primary mb-2"></i>
                                        <p class="mb-3">已到达活动现场？点击下方按钮签到</p>
                                        <button class="btn btn-success w-100 py-2 fw-bold" id="checkinBtn">
                                            <i class="fas fa-check-circle me-2"></i>立即签到
                                        </button>
                                        <small class="text-muted d-block mt-2">签到成功可获得10积分奖励</small>
                                    </div>
                                    {% endif %}
                                {% else %}
                                <!-- 已签到 -->
                                <div class="checkin-status text-center p-3 bg-success text-white rounded">
                                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                                    <h6 class="mb-1">签到成功</h6>
                                    <p class="mb-1">您已成功签到本次活动</p>
                                    <small>获得10积分奖励</small>
                                    <div class="mt-2">
                                        <small>签到时间: {{ checkin_time|date:"m月d日 H:i" }}</small>
                                    </div>
                                </div>
                                {% endif %}
                            {% else %}
                            <!-- 未报名 -->
                            <div class="checkin-status text-center p-3 bg-light rounded">
                                <i class="fas fa-lock fa-2x text-muted mb-2"></i>
                                <p class="mb-2">请先报名活动才能签到</p>
                                {% if can_register %}
                                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#registerModal">
                                    <i class="fas fa-user-plus me-1"></i>立即报名
                                </button>
                                {% endif %}
                            </div>
                            {% endif %}

                            <!-- 签到统计信息 -->
                            {% if user_registered and event.organizer == user %}
                            <div class="checkin-stats mt-3 p-3 bg-light rounded">
                                <h6 class="mb-2">签到统计（组织者）</h6>
                                <div class="d-flex justify-content-between">
                                    <span>已签到人数:</span>
                                    <strong>{{ event.checkins.count }} / {{ event.current_participants }}</strong>
                                </div>
                                <button class="btn btn-outline-primary btn-sm w-100 mt-2" id="viewCheckinList">
                                    <i class="fas fa-list me-1"></i>查看签到列表
                                </button>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 活动基本信息 -->
    <div class="row g-3 mb-3">
        <!-- 左侧：时间地点组织者信息 -->
        <div class="col-md-4">
            <!-- 评分和基本信息 -->
            <div class="card info-card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="d-flex align-items-center">
                            <span class="text-warning me-2">
                                <!-- 修复星星显示：直接显示5个星星 -->
                                {% for i in "12345" %}
                                    {% if forloop.counter <= avg_rating %}
                                        <i class="fas fa-star"></i>
                                    {% else %}
                                        <i class="far fa-star"></i>
                                    {% endif %}
                                {% endfor %}
                            </span>
                            <span class="fw-bold me-3">{{ avg_rating|default:"0" }}</span>
                            <span class="text-muted">({{ reviews.count }}条评价)</span>
                        </div>
                        <div class="d-flex align-items-center text-muted">
                            <i class="fas fa-eye me-1"></i>
                            <span>{{ event.views_count}}浏览</span>
                        </div>
                    </div>
                    <div class="d-flex align-items-center text-muted">
                        <i class="fas fa-users me-2"></i>
                        <span>已报名 <strong class="text-primary" id="participants-count">{{ event.current_participants }}/{{ event.max_participants }}</strong> 人</span>
                    </div>
                </div>
            </div>

            <!-- 时间地点信息 -->
            <div class="card info-card">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="icon-circle me-3">
                            <i class="fas fa-clock text-primary"></i>
                        </div>
                        <div>
                            <div class="fw-bold text-dark">时间</div>
                            <div class="text-muted">{{ event.start_time|date:"m月d日 H:i" }} - {{ event.end_time|date:"H:i" }}</div>
                        </div>
                    </div>

                    <div class="d-flex align-items-center mb-3">
                        <div class="icon-circle me-3">
                            <i class="fas fa-map-marker-alt text-primary"></i>
                        </div>
                        <div>
                            <div class="fw-bold text-dark">地点</div>
                            <div class="text-muted">{{ event.location }}</div>
                        </div>
                    </div>

                    <div class="d-flex align-items-center">
                        <div class="icon-circle me-3">
                            <i class="fas fa-user text-primary"></i>
                        </div>
                        <div class="flex-grow-1">
                            <div class="fw-bold text-dark">组织者：{{ event.organizer.username }}</div>
                            <div class="text-muted small">已组织 {{ event.organizer.organized_events.count }} 个活动</div>
                        </div>
                        <a href="/location/social/messages/{{ event.organizer.id }}/" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-comment me-1"></i>联系
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧：活动描述和评分 -->
        <div class="col-md-8">
            <!-- 活动描述 -->
            <div class="card info-card mb-3">
                <div class="card-body">
                    <div class="card-title-section">
                        <i class="fas fa-file-alt text-primary me-2"></i>
                        <h6 class="card-title fw-bold mb-0">活动描述</h6>
                    </div>
                    <div class="activity-content">
                        {{ event.description }}
                    </div>

                    <!-- 费用信息 -->
                    <div class="mt-3 p-3 bg-light rounded">
                        <i class="fas fa-tag text-primary me-2"></i>
                        <strong>活动费用：</strong>
                        {% if event.is_free %}
                            <span class="text-success fw-bold">免费</span>
                        {% else %}
                            <span class="text-danger fw-bold">¥{{ event.fee }}</span>
                            <small class="text-muted">（包含门票和午餐）</small>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 活动评分 -->
            <div class="card info-card mb-3">
                <div class="card-body">
                    <div class="card-title-section">
                        <i class="fas fa-star text-warning me-2"></i>
                        <h6 class="card-title fw-bold mb-0">活动评分</h6>
                        {% if user_registered %}
                        <small class="text-muted ms-2">(您已报名，可以评分)</small>
                        {% else %}
                        <small class="text-muted ms-2">(报名后可评分)</small>
                        {% endif %}
                    </div>

                    <!-- 评分区域 -->
                    <div class="rating-section" id="rating-section">
                        {% if user_registered %}
                            {% if not has_reviewed %}
                            <div class="rating-input mb-3">
                                <p class="mb-2">给这个活动打分：</p>
                                <div class="star-rating mb-3">
                                    {% for i in "12345" %}
                                    <i class="far fa-star rating-star" data-rating="{{ i }}"></i>
                                    {% endfor %}
                                </div>
                                <div class="rating-text mb-2">
                                    <small class="text-muted" id="ratingText">点击星星进行评分</small>
                                </div>
                            </div>
                            {% else %}
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i>您已经评价过这个活动了
                            </div>
                            {% endif %}
                        {% else %}
                        <div class="text-center py-3">
                            <i class="fas fa-lock fa-2x text-muted mb-3"></i>
                            <p class="text-muted">请先报名活动才能进行评分</p>
                            {% if can_register %}
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#registerModal">
                                <i class="fas fa-user-plus me-2"></i>立即报名
                            </button>
                            {% endif %}
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 评论区 -->
    <div class="card info-card mb-5">
        <div class="card-body">
            <div class="card-title-section">
                <i class="fas fa-comments text-primary me-2"></i>
                <h6 class="card-title fw-bold mb-0">活动讨论区</h6>
                <span class="badge bg-primary ms-2" id="commentsCount">{{ discussions.count }}</span>
            </div>

            <!-- 评论输入框 -->
            <div class="comment-input mb-4">
                <div class="d-flex align-items-start">
                    <div class="flex-grow-1 me-2">
                        <textarea id="commentContent" class="form-control" rows="3"
                                  placeholder="分享你的想法...{% if not user.is_authenticated %} (请先登录){% endif %}"
                                  {% if not user.is_authenticated %}disabled{% endif %}></textarea>
                    </div>
                    <button id="submitComment" class="btn btn-primary"
                            data-event-id="{{ event.id}}"
                            {% if not user.is_authenticated %}disabled{% endif %}>
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
                <div class="mt-2 text-end">
                    <small class="text-muted">按 Enter 发送，Shift + Enter 换行</small>
                    {% if not user.is_authenticated %}
                    <small class="text-warning ms-2">请先登录后评论</small>
                    {% endif %}
                </div>
            </div>

            <!-- 评论列表 -->
            <div id="commentsList">
                {% for discussion in discussions %}
                <div class="comment-item border-bottom pb-3 mb-3" data-comment-id="{{ discussion.id }}">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="d-flex align-items-center">
                            <span class="fw-bold">{{ discussion.user.username }}</span>
                            <small class="text-muted ms-2">{{ discussion.created_at|date:"Y-m-d H:i" }}</small>
                            {% if discussion.is_pinned %}
                            <span class="badge bg-warning ms-2">置顶</span>
                            {% endif %}
                        </div>
                        <div class="comment-actions">
                            {% if discussion.user == user or event.organizer == user %}
                            <button class="btn btn-link text-danger p-0 delete-comment-btn delete-comment"
                                    data-comment-id="{{ discussion.id }}"
                                    title="删除评论">
                                <i class="fas fa-trash"></i>
                            </button>
                            {% endif %}
                        </div>
                    </div>
                    <p class="mb-2">{{ discussion.content }}</p>
                    <div class="d-flex align-items-center">
                        <!-- 点赞按钮 -->
                        <button class="btn btn-link text-muted p-0 me-3 like-comment like-btn {% if discussion.user_liked %}active{% endif %}"
                                data-comment-id="{{ discussion.id }}"
                                {% if not user.is_authenticated %}disabled{% endif %}>
                            <i class="{% if discussion.user_liked %}fas text-primary{% else %}far{% endif %} fa-thumbs-up me-1"></i>
                            <span class="likes-count">{{ discussion.likes_count }}</span>
                        </button>

                        <!-- 踩按钮 -->
                        <button class="btn btn-link text-muted p-0 me-3 dislike-comment dislike-btn {% if discussion.user_disliked %}active{% endif %}"
                                data-comment-id="{{ discussion.id }}"
                                {% if not user.is_authenticated %}disabled{% endif %}>
                            <i class="{% if discussion.user_disliked %}fas text-danger{% else %}far{% endif %} fa-thumbs-down me-1"></i>
                            <span class="dislikes-count">{{ discussion.dislikes_count }}</span>
                        </button>

                        <button class="btn btn-link text-muted p-0 reply-btn"
                                data-comment-id="{{ discussion.id }}"
                                {% if not user.is_authenticated %}disabled{% endif %}>
                            <i class="fas fa-reply me-1"></i>回复
                        </button>
                    </div>

                    <!-- 回复输入框（默认隐藏） -->
                    <div class="reply-input mt-2" style="display: none;">
                        <div class="d-flex align-items-start">
                            <div class="flex-grow-1 me-2">
                                <textarea class="form-control reply-content" rows="2"
                                          placeholder="回复 {{ discussion.user.username }}..."></textarea>
                            </div>
                            <button class="btn btn-primary btn-sm submit-reply">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 回复列表 -->
                    <div class="replies-list mt-2 ms-4" id="replies-{{ discussion.id }}">
                        {% for reply in discussion.replies.all %}
                        <div class="reply-item border-start border-primary ps-3 py-2" data-comment-id="{{ reply.id }}">
                            <div class="d-flex justify-content-between align-items-start mb-1">
                                <div class="d-flex align-items-center">
                                    <span class="fw-bold">{{ reply.user.username }}</span>
                                    <small class="text-muted ms-2">{{ reply.created_at|date:"Y-m-d H:i" }}</small>
                                </div>
                                {% if reply.user == user or event.organizer == user %}
                                <button class="btn btn-link text-danger p-0 delete-comment-btn delete-comment"
                                        data-comment-id="{{ reply.id }}"
                                        title="删除回复">
                                    <i class="fas fa-trash"></i>
                                </button>
                                {% endif %}
                            </div>
                            <p class="mb-1">{{ reply.content }}</p>
                            <div class="d-flex align-items-center">
                                <!-- 回复的点赞按钮 -->
                                <button class="btn btn-link text-muted p-0 me-3 like-comment like-btn {% if reply.user_liked %}active{% endif %}"
                                        data-comment-id="{{ reply.id }}"
                                        {% if not user.is_authenticated %}disabled{% endif %}>
                                    <i class="{% if reply.user_liked %}fas text-primary{% else %}far{% endif %} fa-thumbs-up me-1"></i>
                                    <span class="likes-count">{{ reply.likes_count }}</span>
                                </button>

                                <!-- 回复的踩按钮 -->
                                <button class="btn btn-link text-muted p-0 me-3 dislike-comment dislike-btn {% if reply.user_disliked %}active{% endif %}"
                                        data-comment-id="{{ reply.id }}"
                                        {% if not user.is_authenticated %}disabled{% endif %}>
                                    <i class="{% if reply.user_disliked %}fas text-danger{% else %}far{% endif %} fa-thumbs-down me-1"></i>
                                    <span class="dislikes-count">{{ reply.dislikes_count }}</span>
                                </button>
                            </div>
                        </div>
                        {% endfor %}
                    </div>

                    <!-- 查看更多回复 -->
                    {% if discussion.replies.count > 3 %}
                    <div class="more-replies mt-2 ms-4">
                        <button class="btn btn-link text-primary p-0 load-more-replies"
                                data-comment-id="{{ discussion.id }}">
                            <small>查看全部 {{ discussion.replies.count }} 条回复</small>
                        </button>
                    </div>
                    {% endif %}
                </div>
                {% empty %}
                <div class="text-center text-muted py-4">
                    <i class="fas fa-comments fa-2x mb-2"></i>
                    <p>暂无讨论，快来发表第一条评论吧！</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>

<!-- 固定底部报名按钮 -->
<div class="fixed-bottom border-top p-3">
    {% if user_registered %}
        <button class="btn btn-success w-100 py-3 fw-bold" disabled>
            <i class="fas fa-check me-2"></i>已报名
        </button>
    {% elif can_register %}
        <button class="btn btn-primary w-100 py-3 fw-bold" data-bs-toggle="modal" data-bs-target="#registerModal">
            <i class="fas fa-user-plus me-2"></i>立即报名
        </button>
        <!-- 保留截止时间 -->
        <small class="text-muted d-block text-center mt-2">报名截止：{{ event.registration_deadline|date:"m月d日 H:i" }}</small>
    {% else %}
        <button class="btn btn-secondary w-100 py-3 fw-bold" disabled>
            <i class="fas fa-times me-2"></i>无法报名
        </button>
    {% endif %}
</div>

<!-- 报名模态框 -->
<div class="modal fade" id="registerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">报名{{ event.title }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="mb-3">确认报名参加此活动？</p>
                <div class="alert alert-info">
                    <small>
                        <i class="fas fa-info-circle"></i>
                        报名后可以在"我的活动"中查看和管理报名状态
                    </small>
                </div>
                {% if not event.is_free %}
                <div class="alert alert-warning">
                    <small>
                        <i class="fas fa-exclamation-triangle"></i>
                        此活动需要支付费用：<strong>¥{{ event.fee }}</strong>
                    </small>
                </div>
                {% endif %}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="registerForActivity()">确认报名</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
// 全局变量
let detailMap = null;
let drivingRoute = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    const contentContainer = document.querySelector('.container');
    if (contentContainer) {
        contentContainer.style.paddingBottom = '100px';
    }

    // 初始化地图
    initDetailMap();

    // 初始化评论区
    new CommentSystem();

    // 初始化评分系统 - 只要有星星就初始化
    if (document.querySelector('.rating-star')) {
        new RatingSystem();
    }

    console.log('页面初始化完成');
});

// 初始化详情页地图
function initDetailMap() {
    // 创建地图实例
    detailMap = new BMap.Map("map-container");

    // 使用地理编码服务将地址转换为坐标
    const geocoder = new BMap.Geocoder();
    const address = "{{ event.location }}";  // 使用实际的活动地址

    geocoder.getPoint(address, function(point) {
        if (point) {
            detailMap.centerAndZoom(point, 15);
            detailMap.enableScrollWheelZoom(true);

            // 添加基本控件
            detailMap.addControl(new BMap.NavigationControl());
            detailMap.addControl(new BMap.ScaleControl());

            // 添加活动位置标记
            addActivityMarker(point);
        } else {
            // 如果地理编码失败，使用默认坐标
            const defaultPoint = new BMap.Point(121.47, 31.23); // 上海中心坐标
            detailMap.centerAndZoom(defaultPoint, 10);
            addActivityMarker(defaultPoint);
            console.log('地理编码失败，使用默认坐标');
        }
    }, "上海市"); // 可以指定城市提高准确性
}

// 修改添加标记函数，接收坐标参数
function addActivityMarker(point) {
    const marker = new BMap.Marker(point);

    const content = `
        <div class="map-marker-popup">
            <h6>{{ event.title|default:"周末户外徒步活动" }}</h6>
            <p class="mb-1"><small><i class="fas fa-map-marker-alt"></i> {{ event.location }}</small></p>
            <p class="mb-1"><small><i class="fas fa-clock"></i> {{ event.start_time|date:"m月d日 H:i"}}</small></p>
            <p class="mb-1"><small><i class="fas fa-tag"></i> {% if event.category %}{{ event.category.name }}{% else %}户外运动{% endif %}</small></p>
            <div class="d-flex justify-content-between align-items-center">
                <span class="badge bg-warning">{% if event.is_free %}免费{% else %}¥{{ event.fee }}{% endif %}</span>
            </div>
        </div>
    `;

    const infoWindow = new BMap.InfoWindow(content, {
        width: 200,
        height: 180
    });

    marker.addEventListener("click", function() {
        this.openInfoWindow(infoWindow);
    });

    detailMap.addOverlay(marker);
    marker.openInfoWindow(infoWindow);
}

// 获取CSRF token
function getCsrfToken() {
    const metaToken = document.querySelector('meta[name="csrf-token"]');
    if (metaToken) {
        return metaToken.getAttribute('content');
    }

    const inputToken = document.querySelector('[name=csrfmiddlewaretoken]');
    if (inputToken) {
        return inputToken.value;
    }

    const cookieToken = getCookie('csrftoken');
    if (cookieToken) {
        return cookieToken;
    }

    console.error('无法获取CSRF token');
    return '';
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


// 评分系统
class RatingSystem {
    constructor() {
        this.selectedRating = 0;
        this.isSubmitting = false;
        this.initEventListeners();
    }

    initEventListeners() {
        // 星星点击事件
        document.querySelectorAll('.rating-star').forEach(star => {
            star.addEventListener('click', (e) => {
                if (this.isSubmitting) return;
                const rating = parseInt(e.target.dataset.rating);
                this.setRating(rating);
                // 点击后立即提交
                this.submitRating();
            });

            star.addEventListener('mouseover', (e) => {
                if (this.isSubmitting) return;
                const rating = parseInt(e.target.dataset.rating);
                this.highlightStars(rating);
            });
        });

        // 星星区域鼠标移出事件
        const starRating = document.querySelector('.star-rating');
        if (starRating) {
            starRating.addEventListener('mouseleave', () => {
                if (this.isSubmitting) return;
                this.highlightStars(this.selectedRating);
            });
        }
    }

    setRating(rating) {
        this.selectedRating = rating;
        this.updateStarDisplay();
        this.updateRatingText();
    }

    highlightStars(rating) {
        const stars = document.querySelectorAll('.rating-star');
        stars.forEach((star, index) => {
            const starRating = index + 1;
            if (starRating <= rating) {
                star.className = 'fas fa-star rating-star';
                star.style.color = '#ffc107';
            } else {
                star.className = 'far fa-star rating-star';
                star.style.color = '#e4e5e9';
            }
        });
    }

    updateStarDisplay() {
        this.highlightStars(this.selectedRating);
    }

    updateRatingText() {
        const ratingText = document.getElementById('ratingText');
        const texts = {
            1: '很差',
            2: '一般',
            3: '不错',
            4: '很好',
            5: '非常棒'
        };
        ratingText.textContent = texts[this.selectedRating] || '点击星星进行评分';
        ratingText.className = 'text-warning fw-bold';
    }

    async submitRating() {
        if (this.isSubmitting) return;

        if (this.selectedRating === 0) {
            return;
        }

        const eventId = {{ event.id }};

        this.isSubmitting = true;

        // 显示提交状态
        const ratingText = document.getElementById('ratingText');
        const originalText = ratingText.textContent;
        ratingText.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>提交中...';

        try {
            const response = await fetch('/location/api/reviews/submit/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCsrfToken()
                },
                body: JSON.stringify({
                    event_id: eventId,
                    rating: this.selectedRating,
                    comment: ''  // 空评论，因为我们只需要评分
                })
            });

            const data = await response.json();

            if (data.success) {
                this.showMessage('评分提交成功！', 'success');

                // 禁用星星交互
                document.querySelectorAll('.rating-star').forEach(star => {
                    star.style.cursor = 'default';
                    star.style.pointerEvents = 'none';
                });

                // 更新UI显示已评价状态
                setTimeout(() => {
                    const ratingSection = document.querySelector('.rating-section');
                    ratingSection.innerHTML = `
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>您已经给这个活动打了 ${this.selectedRating} 星评价
                        </div>
                    `;
                }, 1000);

            } else {
                this.showMessage(data.message || '评分提交失败', 'error');
                ratingText.textContent = originalText;
                this.isSubmitting = false;
            }
        } catch (error) {
            console.error('评分提交错误:', error);
            this.showMessage('网络错误，请重试', 'error');
            ratingText.textContent = originalText;
            this.isSubmitting = false;
        }
    }

    showMessage(message, type = 'info') {
        const messageEl = document.createElement('div');
        messageEl.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show mt-3`;
        messageEl.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        const ratingSection = document.querySelector('.rating-section');
        ratingSection.insertBefore(messageEl, ratingSection.firstChild);

        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.remove();
            }
        }, 3000);
    }
}

// 评论区功能
class CommentSystem {
    constructor() {
        this.initEventListeners();
        this.setupKeyboardShortcuts();
    }

    initEventListeners() {
        document.addEventListener('click', (e) => {
            if (e.target.closest('.like-comment')) {
               this.handleLike(e.target.closest('.like-comment'), e);
           }
           if (e.target.closest('.dislike-comment')) {
               this.handleDislike(e.target.closest('.dislike-comment'), e);
           }
            if (e.target.closest('.reply-btn')) {
                this.toggleReplyInput(e.target.closest('.reply-btn'));
            }
            if (e.target.closest('.submit-reply')) {
                this.submitReply(e.target.closest('.submit-reply'));
            }
            if (e.target.closest('.delete-comment')) {
                this.deleteComment(e.target.closest('.delete-comment'));
            }
        });

        const submitCommentBtn = document.getElementById('submitComment');
        if (submitCommentBtn) {
            submitCommentBtn.addEventListener('click', () => this.submitComment());
        }
    }

    setupKeyboardShortcuts() {
        const commentContent = document.getElementById('commentContent');
        if (commentContent) {
            commentContent.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.submitComment();
                }
            });
        }
    }

async handleLike(button) {
    if (!this.checkAuth()) return;

    const commentId = button.dataset.commentId;
    const isActive = button.classList.contains('active');

    try {
        const response = await fetch('/location/api/comments/like/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify({
                discussion_id: commentId,
                action: isActive ? 'unlike' : 'like'
            })
        });

        const data = await response.json();

        if (data.success) {
            const likesCount = button.querySelector('.likes-count');
            const icon = button.querySelector('i');

            if (isActive) {
                button.classList.remove('active');
                icon.className = 'far fa-thumbs-up me-1';
                likesCount.textContent = parseInt(likesCount.textContent) - 1;
            } else {
                button.classList.add('active');
                icon.className = 'fas fa-thumbs-up me-1 text-primary';
                likesCount.textContent = parseInt(likesCount.textContent) + 1;

                // 修复：只在当前评论/回复范围内查找踩按钮
                const container = button.closest('.comment-item, .reply-item');
                const dislikeBtn = container.querySelector('.dislike-comment');
                if (dislikeBtn && dislikeBtn.classList.contains('active')) {
                    this.handleDislike(dislikeBtn, true);
                }
            }
        } else {
            this.showMessage(data.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('点赞请求失败:', error);
        this.showMessage('网络错误，请重试', 'error');
    }
}

async handleDislike(button, silent = false) {
    if (!silent && !this.checkAuth()) return;

    const commentId = button.dataset.commentId;
    const isActive = button.classList.contains('active');

    try {
        const response = await fetch('/location/api/comments/dislike/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify({
                discussion_id: commentId,
                action: isActive ? 'undislike' : 'dislike'
            })
        });

        const data = await response.json();

        if (data.success) {
            const dislikesCount = button.querySelector('.dislikes-count');
            const icon = button.querySelector('i');

            if (isActive) {
                button.classList.remove('active');
                icon.className = 'far fa-thumbs-down me-1';
                dislikesCount.textContent = parseInt(dislikesCount.textContent) - 1;
            } else {
                button.classList.add('active');
                icon.className = 'fas fa-thumbs-down me-1 text-danger';
                dislikesCount.textContent = parseInt(dislikesCount.textContent) + 1;

                // 修复：只在当前评论/回复范围内查找赞按钮
                const container = button.closest('.comment-item, .reply-item');
                const likeBtn = container.querySelector('.like-comment');
                if (likeBtn && likeBtn.classList.contains('active')) {
                    this.handleLike(likeBtn, true);
                }
            }
        } else if (!silent) {
            this.showMessage(data.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('踩请求失败:', error);
        if (!silent) {
            this.showMessage('网络错误，请重试', 'error');
        }
    }
}

    toggleReplyInput(button) {
        const commentItem = button.closest('.comment-item');
        const replyInput = commentItem.querySelector('.reply-input');

        if (replyInput.style.display === 'none' || !replyInput.style.display) {
            replyInput.style.display = 'block';
            replyInput.querySelector('.reply-content').focus();
        } else {
            replyInput.style.display = 'none';
        }
    }

    async submitReply(button) {
        if (!this.checkAuth()) return;

        const commentItem = button.closest('.comment-item');
        const parentId = commentItem.dataset.commentId;
        const replyContent = commentItem.querySelector('.reply-content');
        const content = replyContent.value.trim();

        if (!content) {
            this.showMessage('请输入回复内容', 'warning');
            return;
        }

        try {
            const response = await fetch('/location/api/comments/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCsrfToken()
                },
                body: JSON.stringify({
                    parent_id: parentId,
                    content: content,
                    event_id: document.getElementById('submitComment').dataset.eventId
                })
            });

            const data = await response.json();

            if (data.success) {
                replyContent.value = '';
                commentItem.querySelector('.reply-input').style.display = 'none';
                this.addReplyToDOM(commentItem, data.discussion);
                this.updateRepliesCount(commentItem, 1);
                this.showMessage('回复成功', 'success');
            } else {
                this.showMessage(data.message || '回复失败', 'error');
            }
        } catch (error) {
            console.error('回复请求失败:', error);
            this.showMessage('网络错误，请重试', 'error');
        }
    }

    addReplyToDOM(commentItem, replyData) {
        const repliesList = commentItem.querySelector('.replies-list');
        const moreReplies = commentItem.querySelector('.more-replies');

        const replyHtml = `
            <div class="reply-item border-start border-primary ps-3 py-2" data-comment-id="${replyData.id}">
                <div class="d-flex justify-content-between align-items-start mb-1">
                    <div class="d-flex align-items-center">
                        <span class="fw-bold">${replyData.user.username}</span>
                        <small class="text-muted ms-2">${new Date(replyData.created_at).toLocaleString()}</small>
                    </div>
                    ${replyData.can_delete ? `
                    <button class="btn btn-link text-danger p-0 delete-comment-btn delete-comment"
                            data-comment-id="${replyData.id}"
                            title="删除回复">
                        <i class="fas fa-trash"></i>
                    </button>
                    ` : ''}
                </div>
                <p class="mb-1">${this.escapeHtml(replyData.content)}</p>
                <div class="d-flex align-items-center">
                    <button class="btn btn-link text-muted p-0 me-3 like-comment like-btn"
                            data-comment-id="${replyData.id}">
                        <i class="far fa-thumbs-up me-1"></i>
                        <span class="likes-count">${replyData.likes_count}</span>
                    </button>
                    <button class="btn btn-link text-muted p-0 me-3 dislike-comment dislike-btn"
                            data-comment-id="${replyData.id}">
                        <i class="far fa-thumbs-down me-1"></i>
                        <span class="dislikes-count">${replyData.dislikes_count}</span>
                    </button>
                </div>
            </div>
        `;

        if (moreReplies && repliesList.nextElementSibling === moreReplies) {
            moreReplies.remove();
        }

        repliesList.insertAdjacentHTML('beforeend', replyHtml);

        if (!commentItem.querySelector('.more-replies')) {
            const count = parseInt(repliesList.querySelectorAll('.reply-item').length);
            if (count > 0) {
                const moreHtml = `
                    <div class="more-replies mt-2 ms-4">
                        <button class="btn btn-link text-primary p-0 load-more-replies"
                                data-comment-id="${commentItem.dataset.commentId}">
                            <small>查看全部 ${count} 条回复</small>
                        </button>
                    </div>
                `;
                commentItem.insertAdjacentHTML('beforeend', moreHtml);
            }
        }
    }

    async submitComment() {
        if (!this.checkAuth()) return;

        const commentContent = document.getElementById('commentContent');
        const content = commentContent.value.trim();

        if (!content) {
            this.showMessage('请输入评论内容', 'warning');
            return;
        }

        try {
            const response = await fetch('/location/api/comments/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCsrfToken()
                },
                body: JSON.stringify({
                    content: content,
                    event_id: document.getElementById('submitComment').dataset.eventId
                })
            });

            const data = await response.json();

            if (data.success) {
                commentContent.value = '';
                this.addCommentToDOM(data.discussion);
                this.updateCommentsCount(1);
                this.showMessage('评论成功', 'success');
            } else {
                this.showMessage(data.message || '评论失败', 'error');
            }
        } catch (error) {
            console.error('评论请求失败:', error);
            this.showMessage('网络错误，请重试', 'error');
        }
    }

    addCommentToDOM(commentData) {
        const commentsList = document.getElementById('commentsList');
        const emptyState = commentsList.querySelector('.text-center.text-muted');

        if (emptyState) {
            emptyState.remove();
        }

        const commentHtml = `
            <div class="comment-item border-bottom pb-3 mb-3" data-comment-id="${commentData.id}">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="d-flex align-items-center">
                        <span class="fw-bold">${commentData.user.username}</span>
                        <small class="text-muted ms-2">${new Date(commentData.created_at).toLocaleString()}</small>
                        ${commentData.is_pinned ? '<span class="badge bg-warning ms-2">置顶</span>' : ''}
                    </div>
                    ${commentData.can_delete ? `
                    <div class="comment-actions">
                        <button class="btn btn-link text-danger p-0 delete-comment-btn delete-comment"
                                data-comment-id="${commentData.id}"
                                title="删除评论">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                    ` : ''}
                </div>
                <p class="mb-2">${this.escapeHtml(commentData.content)}</p>
                <div class="d-flex align-items-center">
                    <button class="btn btn-link text-muted p-0 me-3 like-comment like-btn"
                            data-comment-id="${commentData.id}">
                        <i class="far fa-thumbs-up me-1"></i>
                        <span class="likes-count">${commentData.likes_count}</span>
                    </button>
                    <button class="btn btn-link text-muted p-0 me-3 dislike-comment dislike-btn"
                            data-comment-id="${commentData.id}">
                        <i class="far fa-thumbs-down me-1"></i>
                        <span class="dislikes-count">${commentData.dislikes_count}</span>
                    </button>
                    <button class="btn btn-link text-muted p-0 reply-btn"
                            data-comment-id="${commentData.id}">
                        <i class="fas fa-reply me-1"></i>回复
                    </button>
                </div>

                <div class="reply-input mt-2" style="display: none;">
                    <div class="d-flex align-items-start">
                        <div class="flex-grow-1 me-2">
                            <textarea class="form-control reply-content" rows="2"
                                      placeholder="回复 ${commentData.user.username}..."></textarea>
                        </div>
                        <button class="btn btn-primary btn-sm submit-reply">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>

                <div class="replies-list mt-2 ms-4" id="replies-${commentData.id}">
                </div>
            </div>
        `;

        commentsList.insertAdjacentHTML('afterbegin', commentHtml);
    }

    async deleteComment(button) {
        if (!confirm('确定要删除吗？此操作不可撤销。')) {
            return;
        }

        const commentId = button.dataset.commentId;

        try {
            const response = await fetch(`/location/api/comments/${commentId}/`, {
                method: 'DELETE',
                headers: {
                    'X-CSRFToken': getCsrfToken()
                }
            });

            const data = await response.json();

            if (data.success) {
                const commentElement = document.querySelector(`[data-comment-id="${commentId}"]`);

                if (commentElement.classList.contains('reply-item')) {
                    const parentComment = commentElement.closest('.comment-item');
                    commentElement.remove();
                    this.updateRepliesCount(parentComment, -1);
                } else {
                    commentElement.remove();
                    this.updateCommentsCount(-1);

                    const commentsList = document.getElementById('commentsList');
                    if (commentsList.children.length === 0) {
                        const emptyHtml = `
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-comments fa-2x mb-2"></i>
                                <p>暂无讨论，快来发表第一条评论吧！</p>
                            </div>
                        `;
                        commentsList.innerHTML = emptyHtml;
                    }
                }

                this.showMessage('删除成功', 'success');
            } else {
                this.showMessage(data.message || '删除失败', 'error');
            }
        } catch (error) {
            console.error('删除请求失败:', error);
            this.showMessage('网络错误，请重试', 'error');
        }
    }

    updateRepliesCount(commentItem, change) {
        const moreReplies = commentItem.querySelector('.more-replies');
        if (moreReplies) {
            const button = moreReplies.querySelector('.load-more-replies');
            const currentText = button.textContent;
            const match = currentText.match(/查看全部 (\d+) 条回复/);

            if (match) {
                const currentCount = parseInt(match[1]);
                const newCount = currentCount + change;

                if (newCount <= 0) {
                    moreReplies.remove();
                } else {
                    button.innerHTML = `<small>查看全部 ${newCount} 条回复</small>`;
                }
            }
        }
    }

    updateCommentsCount(change) {
        const commentsCount = document.getElementById('commentsCount');
        if (commentsCount) {
            const currentCount = parseInt(commentsCount.textContent);
            commentsCount.textContent = currentCount + change;
        }
    }

    checkAuth() {
        const isAuthenticated = document.getElementById('submitComment').disabled === false;
        if (!isAuthenticated) {
            this.showMessage('请先登录后再操作', 'warning');
            return false;
        }
        return true;
    }

    showMessage(message, type = 'info') {
        const messageEl = document.createElement('div');
        messageEl.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show`;
        messageEl.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        const container = document.querySelector('.container');
        container.insertBefore(messageEl, container.firstChild);

        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.remove();
            }
        }, 5000);
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}



// 积分提示功能
function showPointToast(points, reason) {
    const toast = document.createElement('div');
    toast.className = 'position-fixed bottom-0 end-0 m-3 toast show';
    toast.style.zIndex = '9999';
    toast.style.minWidth = '300px';
    toast.innerHTML = `
        <div class="toast-header bg-success text-white">
            <i class="fas fa-coins me-2"></i>
            <strong class="me-auto">获得积分</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            <div class="d-flex justify-content-between align-items-center">
                <span>${reason}</span>
                <span class="badge bg-warning text-dark fs-6">+${points}</span>
            </div>
        </div>
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 5000);
}
// 签到功能
document.addEventListener('DOMContentLoaded', function() {
    const checkinBtn = document.getElementById('checkinBtn');
    if (checkinBtn) {
        checkinBtn.addEventListener('click', handleCheckin);
    }

    const viewCheckinListBtn = document.getElementById('viewCheckinList');
    if (viewCheckinListBtn) {
        viewCheckinListBtn.addEventListener('click', viewCheckinList);
    }
});

async function handleCheckin() {
    const checkinBtn = document.getElementById('checkinBtn');
    const originalText = checkinBtn.innerHTML;

    checkinBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>签到中...';
    checkinBtn.disabled = true;

    try {
        const response = await fetch('/location/api/checkin/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify({
                event_id: {{ event.id }}
            })
        });

        const data = await response.json();

        if (data.success) {
            // 更新签到状态显示
            const checkinSection = document.querySelector('.checkin-section');
            const currentTime = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });

            checkinSection.innerHTML = `
                <div class="card-title-section mb-3">
                    <i class="fas fa-qrcode text-success me-2"></i>
                    <h6 class="card-title fw-bold mb-0">活动签到</h6>
                </div>
                <div class="checkin-status text-center p-3 bg-success text-white rounded">
                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                    <h6 class="mb-1">签到成功</h6>
                    <p class="mb-1">您已成功签到本次活动</p>
                    <small>获得10积分奖励</small>
                    <div class="mt-2">
                        <small>签到时间: ${currentTime}</small>
                    </div>
                </div>
            `;

            // 显示积分奖励提示
            if (data.points_earned && data.points_earned > 0) {
                showPointToast(data.points_earned, '活动签到奖励');
            }

        } else {
            alert('签到失败: ' + (data.message || '未知错误'));
            checkinBtn.innerHTML = originalText;
            checkinBtn.disabled = false;
        }
    } catch (error) {
        console.error('签到请求失败:', error);
        alert('网络错误，请重试');
        checkinBtn.innerHTML = originalText;
        checkinBtn.disabled = false;
    }
}

async function viewCheckinList() {
    const viewCheckinListBtn = document.getElementById('viewCheckinList');
    const originalText = viewCheckinListBtn.innerHTML;

    // 显示加载状态
    viewCheckinListBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>加载中...';
    viewCheckinListBtn.disabled = true;

    try {
        const response = await fetch(`/location/events/{{ event.id }}/checkin-list/`);
        const data = await response.json();

        // 恢复按钮状态
        viewCheckinListBtn.innerHTML = originalText;
        viewCheckinListBtn.disabled = false;

        if (data.success) {
            // 显示签到列表模态框
            showCheckinModal(data.checkins, data.total_count);
        } else {
            alert('获取签到列表失败: ' + (data.message || '未知错误'));
        }
    } catch (error) {
        console.error('获取签到列表失败:', error);
        // 恢复按钮状态
        viewCheckinListBtn.innerHTML = originalText;
        viewCheckinListBtn.disabled = false;
        alert('网络错误，请重试');
    }
}

function showCheckinModal(checkins, totalCount) {
    // 如果已有模态框，先移除
    const existingModal = document.getElementById('checkinModal');
    if (existingModal) {
        existingModal.remove();
    }

    // 创建模态框HTML
    let modalHTML = `
        <div class="modal fade" id="checkinModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-list-check me-2"></i>签到列表 - 共 ${totalCount} 人
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
    `;

    if (checkins.length > 0) {
        modalHTML += `
            <div class="table-responsive">
                <table class="table table-hover table-sm">
                    <thead class="table-light">
                        <tr>
                            <th width="50">#</th>
                            <th>用户</th>
                            <th width="160">签到时间</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        checkins.forEach((checkin, index) => {
            modalHTML += `
                <tr>
                    <td class="text-muted">${index + 1}</td>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="${checkin.avatar_url}" alt="头像" class="rounded-circle me-2" width="36" height="36" onerror="this.src='/static/images/default-avatar.jpg'">
                            <div>
                                <div class="fw-bold">${checkin.username}</div>
                                <small class="text-muted">ID: ${checkin.user_id}</small>
                            </div>
                        </div>
                    </td>
                    <td class="text-muted">${checkin.checkin_time}</td>
                </tr>
            `;
        });

        modalHTML += `
                    </tbody>
                </table>
            </div>
        `;
    } else {
        modalHTML += `
            <div class="text-center py-5">
                <i class="fas fa-clipboard-list fa-4x text-muted mb-3"></i>
                <h6 class="text-muted">暂无签到记录</h6>
                <p class="text-muted small">还没有用户签到本次活动</p>
            </div>
        `;
    }

    modalHTML += `
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>关闭
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // 显示模态框
    const modalElement = document.getElementById('checkinModal');
    const modal = new bootstrap.Modal(modalElement);
    modal.show();

    // 模态框关闭后清理
    modalElement.addEventListener('hidden.bs.modal', function () {
        this.remove();
    });
}
// 报名功能
function registerForActivity() {
    console.log('=== 开始报名流程 ===');

    const registerBtn = document.querySelector('#registerModal .btn-primary');
    const originalText = registerBtn.innerHTML;
    registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>报名中...';
    registerBtn.disabled = true;

    const eventId = {{ event.id }};
    const csrfToken = getCsrfToken();

    const url = `/location/register/${eventId}/`;

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrfToken,
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({})
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.status === 'success') {
            // 关闭模态框
            $('#registerModal').modal('hide');

            // 更新底部按钮状态
            const bottomBtn = document.querySelector('.fixed-bottom .btn');
            bottomBtn.innerHTML = '<i class="fas fa-check me-2"></i>已报名';
            bottomBtn.className = 'btn btn-success w-100 py-3 fw-bold';
            bottomBtn.disabled = true;

            // 更新报名人数
            const participantsCount = document.getElementById('participants-count');
            if (participantsCount && data.current_participants) {
                participantsCount.textContent = `${data.current_participants}/{{ event.max_participants }}`;
            }

            // 🔥 新增：更新评分区域状态
            updateRatingSectionAfterRegistration();

            // 🔥 新增：更新签到部分状态
            updateCheckinSectionAfterRegistration();

            // 显示成功消息
            alert('报名成功！');

        } else {
            alert('报名失败: ' + (data.message || '未知错误'));
            registerBtn.innerHTML = originalText;
            registerBtn.disabled = false;
        }
    })
    .catch(error => {
        alert('报名请求失败: ' + error.message);
        registerBtn.innerHTML = originalText;
        registerBtn.disabled = false;
    });
}

// 🔥 新增：报名后更新签到区域的函数
function updateCheckinSectionAfterRegistration() {
    const checkinSection = document.querySelector('.checkin-section');

    if (checkinSection) {
        const currentTime = new Date();
        const eventStartTime = new Date('{{ event.start_time|date:"c" }}');
        const eventEndTime = new Date('{{ event.end_time|date:"c" }}');

        let checkinHtml = '';

        if (currentTime < eventStartTime) {
            // 活动未开始
            checkinHtml = `
                <div class="checkin-status text-center p-3 bg-light rounded">
                    <i class="fas fa-clock fa-2x text-warning mb-2"></i>
                    <p class="mb-2">活动尚未开始</p>
                    <small class="text-muted">开始时间: {{ event.start_time|date:"m月d日 H:i" }}</small>
                </div>
            `;
        } else if (currentTime > eventEndTime) {
            // 活动已结束
            checkinHtml = `
                <div class="checkin-status text-center p-3 bg-light rounded">
                    <i class="fas fa-ban fa-2x text-danger mb-2"></i>
                    <p class="mb-2">活动已结束</p>
                    <small class="text-muted">无法签到</small>
                </div>
            `;
        } else {
            // 可以签到
            checkinHtml = `
                <div class="checkin-status text-center p-3 bg-light rounded mb-3">
                    <i class="fas fa-map-marker-alt fa-2x text-primary mb-2"></i>
                    <p class="mb-3">已到达活动现场？点击下方按钮签到</p>
                    <button class="btn btn-success w-100 py-2 fw-bold" id="checkinBtn">
                        <i class="fas fa-check-circle me-2"></i>立即签到
                    </button>
                    <small class="text-muted d-block mt-2">签到成功可获得10积分奖励</small>
                </div>
            `;
        }

        // 替换签到状态部分，但保留标题和组织者统计部分
        const existingStatus = checkinSection.querySelector('.checkin-status');
        if (existingStatus) {
            existingStatus.outerHTML = checkinHtml;
        }

        // 重新绑定签到按钮事件
        const newCheckinBtn = document.getElementById('checkinBtn');
        if (newCheckinBtn) {
            newCheckinBtn.addEventListener('click', handleCheckin);
        }
    }
}

// 🔥 新增：报名后更新评分区域的函数
function updateRatingSectionAfterRegistration() {
    const ratingSection = document.querySelector('.rating-section');

    if (ratingSection) {
        // 替换整个评分区域的内容
        ratingSection.innerHTML = `
            <div class="rating-input mb-3">
                <p class="mb-2">给这个活动打分：</p>
                <div class="star-rating mb-3">
                    <i class="far fa-star rating-star" data-rating="1"></i>
                    <i class="far fa-star rating-star" data-rating="2"></i>
                    <i class="far fa-star rating-star" data-rating="3"></i>
                    <i class="far fa-star rating-star" data-rating="4"></i>
                    <i class="far fa-star rating-star" data-rating="5"></i>
                </div>
                <div class="rating-text mb-2">
                    <small class="text-muted" id="ratingText">点击星星进行评分</small>
                </div>
            </div>
        `;

        // 更新标题提示
        const ratingTitle = document.querySelector('.rating-section').closest('.card-body').querySelector('.text-muted');
        if (ratingTitle) {
            ratingTitle.textContent = '(您已报名，可以评分)';
        }

        // 重新初始化评分系统
        if (window.ratingSystem) {
            window.ratingSystem = new RatingSystem();
        } else {
            // 如果全局变量不存在，直接创建新实例
            new RatingSystem();
        }
    }
}
</script>
{% endblock %}
[file content end]